import sys
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO
from io import open
import io

# pip install pdfminer3k

#sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')


def readPDF(pdfFile):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, laparams=laparams)

    process_pdf(rsrcmgr, device, pdfFile)
    device.close()

    content = retstr.getvalue()
    retstr.close()
    return content



def conver_pdf_to_txt(pdf_path_or_byte):
    if type(pdf_path_or_byte) == str:
        pdf_path_or_byte = open(pdf_path_or_byte, 'rb')

    txt = readPDF(pdf_path_or_byte)
    return txt

if __name__ == '__main__':



    from io import BytesIO
    a = open('document.pdf', 'rb')
    print(type(a))
    # print(a)
    e = a.read()
    print(type(e))
    c = BytesIO(e)
    d = conver_pdf_to_txt(c)
    print(d)
    #print(conver_pdf_to_txt(a))
    #txt = readPDF(open('document.pdf', 'rb'))
